import React, { useEffect, useState, useCallback } from 'react';
import { Empty, Button, Spin } from 'antd';
import { connect } from 'dva';
import CustomForm from '@/components/customForm/CustomForm';
import { openNotificationWithIcon } from 'utils/comm';

const defaultOnCancel = () => {
  window.parent.postMessage({type: 'backFromApply'}, '*');
};
const containerStyle = {
  width: '100%',
  // height: '100%',
  display: 'flex',
  justifyContent: 'center',
  // alignItems: 'center',
  background: '#fff',
};
const NewApply = (props) => {
  const [{ hasForm, error }, setState] = useState({
    hasForm: undefined,
    error: false,
  });
  const {
    location: {
      query: { procDefKey: processDefinitionKey = '' },
    },
    loading,
    dispatch,
    onCancel = defaultOnCancel,
    FlowExecutionStore: { taskformFields = [] } = {},
  } = props;
  const startLoading = loading.effects['FlowExecution/processStart'] || false;
  const formLoading = loading.effects['FlowExecution/getForm'] || false;

  const handleFormSave = useCallback((values) => {
    const payload = {
      variables: values,
      processDefinitionKey,
    };
    dispatch({
      type: "FlowExecution/processStart",
      payload,
    }).then(({ errCode, errMsg }) => {
      if (errCode !== 0) {
        openNotificationWithIcon("error", "", errMsg || "申请提交失败");
      } else {
        openNotificationWithIcon("success", "", "申请提交成功");
        onCancel();
      }
    });
  }, [dispatch, onCancel]);

  const loadData = useCallback(() => {
    dispatch({
      type: "FlowExecution/getForm",
      payload: { processDefinitionKey },
    }).then(({ errCode, errMsg, datas }) => {
      if (errCode !== 0) {
        openNotificationWithIcon(
          'error',
          '',
          errMsg || '获取处理表单信息失败',
        );
        setState({ error: true })
      } else {
        setState({
          hasForm: Boolean(datas && JSON.stringify(datas) !== "{}"),
          error: false,
        });
      }
      window.parent.postMessage({ type: 'height', data: document.documentElement.scrollHeight }, '*');
    });
  }, [dispatch]);

  useEffect(loadData, []);

  if (error || hasForm === false) {
    return (
      <div style={containerStyle}>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={error ? '获取处理表单信息失败' : '当前暂无表单，可点击直接发起申请'}
        >
          <Button
            type="primary"
            style={{marginRight: 12}}
            onClick={error ? loadData : () => handleFormSave({})}
          >
            {error ? '重新加载' : '发起申请'}
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Empty>
      </div>
    );
  }

  if (hasForm) {
    return (
      <div style={{ background: '#ffffff', padding: 12 }}>
        <CustomForm
          title="发起申请"
          confirmLoading={startLoading}
          onOk={(values) => {
            handleFormSave(values);
          }}
          onCancel={onCancel}
          formConfigData={taskformFields}
          dataLoading={formLoading}
          emptyWord="当前无表单，可直接申请"
          action="申请"
          withModal={false}
        />
      </div>
    );
  }

  return <div style={containerStyle}><Spin /></div>;

};

export default connect(
  ({ FlowExecution, appListMenu, loading, Public }) => ({
    FlowExecutionStore: FlowExecution,
    loading,
    menuAppStore: appListMenu,
    focusApp: appListMenu.focusApp,
    menuDataList: Public.menuDataList,
    resourceList: Public.resourceList,
  })
)(NewApply);
